package com.zhu.mall.product.service.impl;

import com.zhu.mall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhu.common.utils.PageUtils;
import com.zhu.common.utils.Query;

import com.zhu.mall.product.dao.CategoryDao;
import com.zhu.mall.product.entity.CategoryEntity;
import com.zhu.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子的树形结构

        //2.1、找到所有的一级分类
        List<CategoryEntity> leve1Menus = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{ //将所有子分类保存在menu中并返回。 再将一级分类收集成List<CategoryEntity>重新返回。
            menu.setChildren(getChildrens(menu,entities));
            return menu;
            //菜单的排序
        }).sorted((menu1,menu2)->{
            return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() ==null ? 0:menu2.getSort());
        }).collect(Collectors.toList());

        return leve1Menus;
    }

    //批量删除
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  //检查当前删除的菜单，是否被其他地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //根据当前分类id找到它的所有父级id  例子：[255/25/2]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        //list收集所有当前分类id的所有父级id
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        //收集到的顺序是[255,35,3]反转为 [3, 37, 255]
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        //先更新自己表中的分类名，再更新与该分类名关联的表数据
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //用list递归收集所有分类的父id
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //先收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        //再判断当前分类是否还有父级分类
        if(byId.getParentCid() != 0){
            //递归收集
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    //递归找到每一个菜单的子菜单       CategoryEntity root当前菜单，List<CategoryEntity> all所有菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((categoryEntity -> {
            //每个子菜单下面可能还会有它的子菜单，再递归查找下去
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
            //菜单的排序
        })).sorted((menu1,menu2)->{
            return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() ==null ? 0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }
}